package com.llap.exp190929.service;

import com.llap.exp190929.entity.Category;
import com.llap.exp190929.entity.Document;
import com.llap.exp190929.repository.DocumentRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class DocumentService {
    private DocumentRepository documentRepository;
    private CategoryService categoryService;

    public Document findDocument(int id) {
        return documentRepository.findById(id).orElse(null);
    }

    public Page<Document> findDocuments(int page, int pageSize, int categoryId) {
        if (categoryId > -1) {
            Category category = new Category();
            category.setId(categoryId);
            return documentRepository.findAllByCategory(category, PageRequest.of(page - 1, pageSize));
        }
        return documentRepository.findAll(PageRequest.of(page - 1, pageSize));
    }

    @Transactional
    public Document addDocument(Document document) {
        if (document.getId() != null) return null;
        return documentRepository.save(document);
    }

    @Transactional
    public Document updateDocument(Document document) {
        if (document.getId() == null) return null;
        return documentRepository.save(document);
    }

    @Transactional
    public void deleteDocument(int id) {
        documentRepository.deleteById(id);
    }
}
